﻿using crip.Services.Repositorys;
using Microsoft.Data.SqlClient;

namespace crip.Services
{
    public class TimedHostedService : IHostedService, IDisposable
    {
        private int executionCount = 0;
        private readonly ILogger<TimedHostedService> _logger;
        private Timer _timer = null!;

        public TimedHostedService(ILogger<TimedHostedService> logger)
        {
            _logger = logger;
          
         }

        public Task StartAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("托管服务启动");
            _timer = new Timer(DoWork, null, TimeSpan.Zero,
                TimeSpan.FromSeconds(5));
            return Task.CompletedTask;
        }

        private async void DoWork(object? state)
        {
            var count = Interlocked.Increment(ref executionCount);
            CheckStatusServices checkStatusServices = new CheckStatusServices();
            await checkStatusServices.CheckEventStatus();

            _logger.LogInformation(
                "托管服务正在运行  执行次数: {Count}", count);
        }


        public Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("托管服务停止");

            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }

    }
}
